package user.com.service.impl;



import com.Exception.GlobalException;
import com.responseData.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import user.com.service.MsgService;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import user.com.utils.CodeCreator;

@Service
public class MsgServiceImpl implements MsgService {

    //发送人
    private String from = "xwj2069181070@163.com";

    //标题
    private String subject = "尊敬用户，你的唯一生成码为:";

    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void sendMsg(String to) throws Exception {

        if(to == null){
            throw new GlobalException(ResponseData.error("传入为空")) ;
        }

        try {
            MimeMessage message = javaMailSender.createMimeMessage() ;
            MimeMessageHelper helper = new MimeMessageHelper(message,true);

            helper.setFrom(from);

            helper.setTo(to);

            helper.setSubject(subject);
            Object code = null;
            try {
                code = redisTemplate.opsForValue().get("code" + to);
            }catch (Exception e){
                e.printStackTrace();
                throw new GlobalException(ResponseData.error("从redis获取数据失败"));
            }

            helper.setText((code == null ? CodeCreator.getInstance().getCode(to) : code.toString()) + "\n2分钟内有效" +"\n");
            javaMailSender.send(message);

        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }
    }

}
